﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using HtmlAgilityPack;
using Wulong.Phone.Dianping.Constants;
using Wulong.Phone.Dianping.Models;

namespace Wulong.Phone.Dianping.Services
{
    public class GroupOnService
    {
        public static IObservable<GroupOn> ObservableHotGroupOn(string cityPinyin, bool receivedAll)
        {
            var url = CommonConstants.GroupOnPage + "/" + cityPinyin;
            
            var queryUrl = new Uri(url);//YqlHelper.HtmlQuery(
                //url, 
                //"//div[@class='box deal-StyleB Left' or @class='box deal-StyleB Right']//div[@class='deal-main']",
                //start, offset);
            return from request in Observable.Return((HttpWebRequest)WebRequest.Create(queryUrl))
                   from response in Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)()
                   from item in GetHotGroupOnItem(response.GetResponseStream()).ToObservable()
                   .ObserveOn(Scheduler.ThreadPool)
                   select item;
        }

        private static IEnumerable<GroupOn> GetHotGroupOnItem(Stream stream)
        {
            var html = new HtmlDocument();
            html.Load(stream);
            var items = html.DocumentNode.Descendants("div")
                .Where(x=>x.HasAttributes
                && x.Attributes[0].Value.Contains("box deal-StyleB"));

            foreach (var item in items)
            {
                var results = item.Descendants("div").Where(x => x.Attributes[0].Value == "deal-main");
                foreach (var result in results)
                {
                    var groupOn = new GroupOn();
                    var dealNodes = result.Descendants("div").Where(x => x.Attributes[0].Value == "");
                    foreach (var dealNode in dealNodes)
                    {
                        var linkNode = dealNode.Descendants("a").FirstOrDefault();
                        if (linkNode != null)
                            groupOn.Link = linkNode.GetAttributeValue("href", "");
                        var imgNode = dealNode.Descendants("img").FirstOrDefault();
                        if (imgNode != null)
                            groupOn.ImageUrl = imgNode.GetAttributeValue("src", "");
                        var descNode = dealNode.Descendants("img").FirstOrDefault();
                        if (descNode != null)
                            groupOn.Desc = descNode.GetAttributeValue("alt", "");
                    }
                    var priceNodes = result.Descendants("div").Where(x => x.Attributes[0].Value == "buy");
                    foreach (var node in priceNodes)
                    {
                        var priceNode = node.Descendants("strong").FirstOrDefault();
                        if (priceNode != null)
                            groupOn.Price = priceNode.InnerText.Replace("&#165;", "");
                        var originalPriceNode = node.Descendants("div").FirstOrDefault();
                        if (originalPriceNode != null)
                            groupOn.OriginalPrice = originalPriceNode.InnerText;
                    }

                    var countNodes = result.Descendants("div").Where(x => x.Attributes[0].Value == "deal-infor Fix");
                    foreach (var node in countNodes)
                    {
                        var soldNode = node.Descendants("p")
                            .FirstOrDefault();
                        if (soldNode != null)
                        {
                            var firstOrDefault = soldNode
                                .Descendants("span")
                                .FirstOrDefault();
                            if (firstOrDefault != null)
                                groupOn.ItemsSold = firstOrDefault.InnerText;
                        }
                        var countNode = node.Descendants("div").FirstOrDefault();
                        if (countNode != null)
                            groupOn.CountDown = countNode.InnerText;
                    }
                    yield return groupOn;
                }
            }
            
        }
    }
}
